package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.ProductType;
import cn.wolfcode.trip.base.query.ProductQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import cn.wolfcode.trip.base.service.IProductTypeService;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;
    @Autowired
    private IProductTypeService productTypeService;

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") ProductQueryObject qo){
        qo.setOrderBy("p.addTime desc");
        model.addAttribute("result",productService.query(qo));
        model.addAttribute("productTypes",productTypeService.listAll());
        return "product/list";
    }

    //推荐游记的新增和修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Product entity, MultipartFile img) {
        //判断有没有设置封
        if (img != null && img.getSize() > 0 && img.getContentType().startsWith("image")){
            //把图片上传到本地图库,返回图片路径
            String url = UploadUtil.upload(img);
            //替换以前默认的封面
            entity.setCoverUrl(url);
        }
        productService.saveOrUpdate(entity);
        return "redirect:/product/list.do";
    }
}
